import React, {Component, PropTypes} from 'react';

import styles from './style.scss';

import Layout from './../Layout';

import ProgressBar from './../Progress';

export default  class Player extends Component {

    constructor( props ) {
        super();
        this.state = {
            start: true,
            canContrl: false,
            //所有的播放队列
            allTargets:[],
            //当前播放的歌曲内容
            playTarget:{},
            show:false,
            duration:0,
            currentTime:0,
            maxShow:false,
        };

        this.playEnded = this.playEnded.bind(this);
        this.playError = this.playError.bind(this);
        this.canPlayMusic = this.canPlayMusic.bind(this);
    }

    timeArray= [];

    componentWillMount(){
        window.wyMusic.playMusic = ({ target = [] , list = {} }) => {
            this.openPlayer({ target , list })
        };
        this.init();
    }

    init(){
        this.audio = new Audio();
        this.audio.addEventListener("ended",this.playEnded, false);
        this.audio.addEventListener("loadedmetadata", this.canPlayMusic, false);
        this.audio.addEventListener("error",this.playError,false);
    }

    openPlayer( { target ,list } ) {

        let { state } = this;

        //如果当前歌曲不存在
        if( Object.keys(target).length <= 0 ) {
            return false;
        }

        const { show , playTarget } = state;

        //延迟300毫秒把layout收起60px

        !show && this.timeArray.push({
            type:"timeout",
            time:setTimeout(() => {
                wyMusic.changeLayoutBottomRange(60);
            },300)
        });

        this.clearTime();

        this.setState({
            show:true,
            playTarget:target
        }, () => {
            const find = this.getPlayTarget(target);
            //如果有列表存在
            if(!!find && playTarget.id !== target.id) {
                this.playMusic( target );
            } else  {
                this.getMusicList( list , target );
            }
        });
    }

    getPlayTarget( { id } ) {
        const { allTargets } = this.state;
        return allTargets.find(item=>item.id===id);
    }

    playMusic( target ){
        this.setState({
            duration:0,
            currentTime:0,
            playTarget:this.getPlayTarget(target)
        },()=>this.loadAudio());
    }

    componentDidMount() {

    }

    getMusicList( list , target ){
        list = !!list.length ? list : [].concat(target);
        Ajax.get({
            url:`/music/url`,
            data:{
                id:list.map(item=>item.id).join(",")
            }
        }).then(( { data } ) => {
            let allTargets = data.map(({ id , url }) => {
                let find = list.find(item=> item.id === id);
                return {
                    ...find,
                    url:url
                };
            });
            this.setState({
                allTargets:allTargets
            },() => {
                this.playMusic(target)
            });
        });
    }

    loadAudio() {
        const { playTarget } = this.state;
        if(!playTarget.url ) return false;
        this.audio.src = playTarget.url;
        this.setState({
            start:true,
            canContrl:false
        });
    }

    canPlayMusic() {
        const { duration } = this.audio;
        this.setState({
            canContrl: true,
            duration:duration
        }, () => {
            this.audio.play();
            this.setPlayTime();
        });
    }

    setPlayTime(){
       this.setCurrentTime();
       this.timeArray.push({
           type:"interval",
           time:setInterval( () => this.setCurrentTime() ,1000 )
       });
    }

    setCurrentTime() {
        const { currentTime } = this.audio;
        this.setState({ currentTime });
    }

    playError(){
        this.playNextMusic();
    }

    playEnded(){
        this.playNextMusic();
    }

    playNextMusic(){
        const { playTarget , allTargets } = this.state;
        let index = allTargets.findIndex(item=>item.id===playTarget.id) + 1;
        this.clearTime();
        if(index > allTargets.length - 1 ) return;
        this.playMusic(allTargets[index]);
    }

    removeListener() {
         if(!!this.audio) {
             this.audio.removeEventListener("canplaythrough", this.canPlayMusic, false);
             this.audio.removeEventListener("ended", this.playEnded, false);
             this.audio.removeEventListener("error", this.playError, false);
         }
    }

    contrl() {
        const {start, canContrl} = this.state;
        canContrl && this.setState({
            start: !start
        }, () => {
            if(!start) {
                this.audio.play();
                this.setPlayTime();
            } else {
                this.audio.pause();
                this.playTime && clearTimeout(this.playTime)
            }
        })
    }

    getForMatTime( time ){
        let mm = ~~( time / 60);
        let ss = ~~(time - mm * 60);
        mm = mm < 10 ? `0${mm}`:mm;
        ss = ss < 10 ? `0${ss}`:ss;
        return `${mm}:${ss}`;
    }

    progressChange(percentage){
        const { duration } = this.state;
        this.audio.currentTime = duration * percentage;
    }

    getPlayPercentage(){
        const { duration , currentTime } = this.state;
        return duration <=0 ? 0 : currentTime / duration;
    }

    clearTime() {
        this.timeArray.forEach(({ type , time }) => {
            type ==="timeout" ?  clearTimeout(time) : clearInterval(time);
        });
    }

    render() {
        const {
            start,
            canContrl ,
            playTarget ,
            show ,
            duration ,
            currentTime ,
            maxShow,
        } = this.state;
        return (
           <div>
               <div className={classname(styles.player_wrapper,show && styles.player_show)}>
                   <div className={styles.min_player}>
                       <div className={styles.min_player_left}
                            onClick={()=>{
                                this.setState({
                                    maxShow:true
                                })
                            }}
                       >
                           <div
                               className={styles.min_player_music_cover}
                               style={playTarget.picUrl ?{backgroundImage:`url(${playTarget.picUrl})`}:null}
                           />
                           <div className={styles.min_player_info}>
                               <p>{playTarget.name}</p>
                               <p>{playTarget.ar}</p>
                           </div>
                       </div>
                       <div className={styles.min_player_right}>
                           <div className={styles.progress_circle}>
                               {canContrl &&
                               <svg width="32"
                                    height="32"
                                    viewBox="0 0 100 100"
                                    version="1.1"
                                    xmlns="http://www.w3.org/2000/svg"
                               >
                                   <circle r="50" cx="50" cy="50" fill="transparent"
                                           className={styles.progress_background}
                                   />
                                   <circle r="50" cx="50" cy="50" fill="transparent"
                                           strokeDasharray="314"
                                           strokeDashoffset={(1-this.getPlayPercentage()) * 314}
                                           className={styles.progress_bar}
                                   />
                               </svg>
                               }
                               <div
                                   onClick={() => this.contrl()}
                                   className={classname(
                                       styles.min_player_control,
                                       canContrl ? (start ?
                                               styles.min_player_control_pause :
                                               styles.min_player_control_start
                                           ):
                                           styles.min_player_control_loading
                                   )}
                               />
                           </div>
                       </div>
                   </div>
               </div>
               {show && maxShow &&<Layout className={styles.player_max_wrapper}>
                   <div className={styles.background}>
                       <img src={playTarget.picUrl} alt=""/>
                   </div>
                   <div className={styles.max_top}>
                       <div className={styles.back} onClick={()=>{
                           this.setState({
                               maxShow:false
                           })
                       }} />
                       <div className={styles.max_title}>{playTarget.name}</div>
                       <div className={styles.max_ar}>{playTarget.ar}</div>
                   </div>
                   <div className={styles.max_center_cover}>
                       <img src={playTarget.picUrl}/>
                   </div>
                   <div className={styles.progress_bar}>
                       <span>{this.getForMatTime(currentTime)}</span>
                       <ProgressBar
                           percentage={this.getPlayPercentage()}
                           onChange={(e)=>this.progressChange(e)}
                       />
                       <span>{this.getForMatTime(duration)}</span>
                   </div>
               </Layout>}
           </div>
        )
    }
}
